<template>
  <div class="thumbnail-selector">
    <!-- 使用两栏布局 -->
    <el-row :gutter="20">
      <!-- 左侧上传和预览区域 -->
      <el-col :span="10">
        <div class="left-panel">
          <h3>上传缩略图</h3>
          <el-alert
            type="info"
            show-icon
            class="mb-4"
          >
            网站缩略图必须先上传到网站，输入图片地址或者点击下面文章中的配图，然后点击上传按钮，在右侧选择已上传的图片作为缩略图。
          </el-alert>
          <!-- AI生成插图按钮 -->
          <div class="ai-generate-section">
            <h4>AI生成插图</h4>
            <!-- 使用AITask组件 -->
            <AITask
              :task-name="'ai_task_feature_image_generate'"
              :api-url="'/cms/api/ai_task_feature_image_generate/'"
              :params="aiTaskParams"
              :button-text="postId ? '根据文章内容生成插图' : '使用通用风格生成插图'"
              :button-icon="'el-icon-magic-stick'"
              :button-type="'primary'"
              :dialog-title="'AI生成特色图片'"
              :dialog-width="'60%'"
              :show-name="'AI智能生成文章特色图片'"
              @result="handleAIGenerateResult"
              @apply="handleAIGenerateApply"
            />
            <p class="ai-tip">{{ postId ? 'AI将根据文章内容自动生成相关插图' : '将使用通用提示词生成插图' }}</p>
          </div>

          <div class="article-images">
            <h4>文章中的图片</h4>
            <div class="images-grid-container">
              <div v-for="(item, index) in imagesurls" :key="index" class="image-item">
                <el-image
                  :src="item"
                  style="width: 100px; height: 100px; cursor: pointer;"
                  @click="handleImageClick(item)"
                />
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-upload2"
                  class="image-upload-btn"
                  :loading="uploadingImages[item]"
                  @click="handleImageUpload(item)"
                >
                  上传
                </el-button>
              </div>
            </div>
          </div>
          <!-- 上传输入框 -->
          <el-input
            v-model="imgurl"
            placeholder="输入图片地址"
            clearable
            size="mini"
            class="mb-4"
            @keyup.native.enter="handleUpload"
          >
            <el-button
              slot="append"
              icon="el-icon-upload2"
              :loading="uploadloading"
              @click="handleUpload"
            >
              上传
            </el-button>
          </el-input>

          <!-- 预览区域 -->
          <div v-if="selectedImagelink" class="preview-panel">
            <h4>从下列选择一张图片作为缩量图:</h4>
            <div class="preview-image">
              <img :src="selectedImagelink" width="100%" height="auto">
            </div>
          </div>
        </div>
      </el-col>

      <!-- 右侧图片列表 -->
      <el-col :span="14">
        <div class="right-panel">
          <h4>已上传图片列表</h4>
          <!-- 添加加载指示器 -->
          <div v-loading="listLoading" element-loading-text="加载中..." class="scrollable-container">
            <!-- 图片网格展示 -->
            <el-table
              :data="data"
              border
              fit
              highlight-current-row
              class="image-table"
              :height="400"
              @current-change="handleCurrentChange"
              @sort-change="handleSort"
            >
              <el-table-column
                align="center"
                label="图片预览"
                width="180"
              >
                <template v-slot="scope">
                  <div class="image-cell">
                    <img
                      :src="scope.row.link"
                      class="preview-thumbnail"
                      @click="handleCurrentChange(scope.row)"
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="操作"
                width="120"
              >
                <template v-slot="scope">
                  <el-button
                    type="primary"
                    size="small"
                    plain
                    icon="el-icon-check"
                    @click="handleCurrentChange(scope.row)"
                  >
                    选择
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页器 -->
            <el-pagination
              v-if="data.length"
              background
              :current-page="page"
              :page-sizes="[10,20,50,100]"
              :page-size="pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              class="pagination"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { Get, Post } from '@/api/cms/wpattachment'
import qs from 'qs'
import request from '@/utils/request'
import AITask from '@/components/AITask'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'Wpattachment',
  components: { AITask },
  props: ['account_id', 'imagesurls', 'articleContent', 'articleTitle', 'postId'],
  data() {
    return {
      data: [],
      listLoading: true,
      imgurl: '',
      order_by: 'create_at',
      order_desc: 1,
      pagesize: 5,
      page: 1,
      total: 0,
      uploadloading: false,
      selectedImagelink: '',
      uploadingImages: {} // 追踪每个图片的上传状态
    }
  },
  computed: {
    // AITask组件需要的参数
    aiTaskParams() {
      const params = {
        style: 'professional' // 默认风格
      }

      // 如果有post_id，传递post_id
      if (this.postId) {
        params.post_id = this.postId
      } else {
        // 没有post_id时，使用自定义提示词
        params.post_id = 0
        params.custom_prompt = this.articleContent || '生成一张适合作为文章特色图片的高质量插图'
      }

      return params
    }
  },
  watch: {
    account_id(v) {
      if (v > 0) {
        this.getList()
      } else {
        this.data = []
        this.listLoading = false
        this.imgurl = ''
        this.selectedImagelink = ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetTemp() {
      this.imgurl = ''
    },
    getList() {
      if (this.account_id <= 0) {
        console.log('account id is not valid')
        return
      }
      this.listLoading = true
      this.selectedImagelink = ''
      Get(null, qs.stringify({
        kw: this.imgurl,
        account_id: this.account_id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    handleCurrentChange(val) {
      if (val) {
        this.selectedImagelink = val.link
        // 确保事件名称正确
        this.$emit('wpattachmentSelectChange', val)
      }
    },
    async handleUpload() {
      if (this.account_id <= 0) {
        this.$message.error('WordPress账户ID无效，请检查配置')
        return
      }

      if (!this.imgurl || !this.imgurl.trim()) {
        this.$message.error('请输入有效的图片URL地址')
        return
      }

      // 验证URL格式
      try {
        new URL(this.imgurl)
      } catch (e) {
        this.$message.error('图片URL格式无效，请检查地址')
        return
      }

      this.uploadloading = true

      // 重试机制：最多重试3次
      const maxRetries = 3
      let retryCount = 0

      const attemptUpload = async() => {
        try {
          await Post({
            link: this.imgurl,
            account_id: this.account_id
          })

          this.resetTemp()
          this.$emit('reload')
          this.notify('缩略图上传成功！')
          this.getList()
          this.uploadloading = false
        } catch (err) {
          retryCount++
          console.error(`Upload attempt ${retryCount} failed:`, err)

          if (retryCount < maxRetries) {
            this.$message.warning(`上传失败，正在重试 (${retryCount}/${maxRetries})...`)
            // 延迟重试，逐渐增加延迟时间
            await new Promise(resolve => setTimeout(resolve, retryCount * 2000))
            return attemptUpload()
          } else {
            // 所有重试都失败了
            this.uploadloading = false
            await this.handleUploadError(err)
          }
        }
      }

      await attemptUpload()
    },

    async handleUploadError(error) {
      let errorMessage = '上传失败：'
      let detailMessage = ''

      if (error.response) {
        // 服务器返回错误响应
        const status = error.response.status
        const data = error.response.data

        switch (status) {
          case 400:
            errorMessage += '请求参数错误'
            detailMessage = data.msg || '图片URL格式可能不正确'
            break
          case 401:
            errorMessage += 'WordPress认证失败'
            detailMessage = 'WordPress用户名或密码错误，请检查账户配置'
            break
          case 403:
            errorMessage += '权限不足'
            detailMessage = 'WordPress用户权限不足，无法上传媒体文件'
            break
          case 404:
            errorMessage += 'WordPress站点无法访问'
            detailMessage = '请检查WordPress站点地址是否正确'
            break
          case 408:
          case 504:
            errorMessage += '请求超时'
            detailMessage = '网络连接超时，请检查网络状况或稍后重试'
            break
          case 500:
            errorMessage += 'WordPress服务器内部错误'
            detailMessage = 'WordPress站点可能遇到问题，请联系站点管理员'
            break
          default:
            errorMessage += `服务器错误 (${status})`
            detailMessage = data.msg || '未知服务器错误'
        }
      } else if (error.code === 'ECONNABORTED') {
        errorMessage += '请求超时'
        detailMessage = '图片下载或上传超时，请检查图片大小和网络状况'
      } else if (error.message) {
        errorMessage += error.message
        detailMessage = '网络连接异常，请检查网络设置'
      } else {
        errorMessage += '未知错误'
        detailMessage = '请稍后重试或联系技术支持'
      }

      // 显示错误提示
      this.$message.error(errorMessage)

      // 显示详细错误信息的通知
      this.$notify({
        title: '缩略图上传失败',
        message: `${errorMessage}\n详细信息: ${detailMessage}`,
        type: 'error',
        duration: 10000,
        position: 'bottom-right'
      })

      // 发送钉钉通知
      await this.sendDingTalkNotification(errorMessage, detailMessage, error)
    },

    async sendDingTalkNotification(errorMessage, detailMessage, originalError) {
      try {
        // 构建钉钉消息内容
        const notificationData = {
          type: 'wp_attachment_upload_error',
          title: 'WordPress缩略图上传失败',
          message: {
            error_message: errorMessage,
            detail_message: detailMessage,
            image_url: this.imgurl,
            account_id: this.account_id,
            timestamp: new Date().toISOString(),
            user_agent: navigator.userAgent,
            error_details: originalError.response ? {
              status: originalError.response.status,
              data: originalError.response.data
            } : originalError.message
          },
          project_id: this.$store.getters.projectId
        }

        // 发送钉钉通知的API调用
        await request({
          url: '/api/notifications/dingtalk/',
          method: 'post',
          data: notificationData,
          timeout: 10000
        })
      } catch (notificationError) {
        console.error('Failed to send DingTalk notification:', notificationError)
      }
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    handleImageClick(item) {
      this.imgurl = item
    },
    async handleImageUpload(imageUrl) {
      if (this.account_id <= 0) {
        this.$message.error('WordPress账户ID无效，请检查配置')
        return
      }

      if (!imageUrl || !imageUrl.trim()) {
        this.$message.error('图片URL无效')
        return
      }

      // 验证URL格式
      try {
        new URL(imageUrl)
      } catch (e) {
        this.$message.error('图片URL格式无效，请检查地址')
        return
      }

      // 设置该图片的上传状态
      this.$set(this.uploadingImages, imageUrl, true)

      // 重试机制：最多重试3次
      const maxRetries = 3
      let retryCount = 0

      const attemptUpload = async() => {
        try {
          await Post({
            link: imageUrl,
            account_id: this.account_id
          })

          this.$emit('reload')
          this.$message.success('图片上传成功！')
          this.getList()
          this.$set(this.uploadingImages, imageUrl, false)
        } catch (err) {
          retryCount++
          console.error(`Upload attempt ${retryCount} failed:`, err)

          if (retryCount < maxRetries) {
            this.$message.warning(`上传失败，正在重试 (${retryCount}/${maxRetries})...`)
            // 延迟重试，逐渐增加延迟时间
            await new Promise(resolve => setTimeout(resolve, retryCount * 2000))
            return attemptUpload()
          } else {
            // 所有重试都失败了
            this.$set(this.uploadingImages, imageUrl, false)
            await this.handleUploadError(err)
          }
        }
      }

      await attemptUpload()
    },
    // 处理AI生成结果
    handleAIGenerateResult(result) {
      console.log('AI生成插图结果:', result)
      // AITask组件会自动显示结果，这里可以做额外处理
    },

    // 处理AI生成应用（当用户点击应用按钮时）
    async handleAIGenerateApply(result) {
      try {
        // 解析AI生成的结果
        if (result && result.includes('<!--FINAL_RESULT:')) {
          const finalResultMatch = result.match(/<!--FINAL_RESULT:\s*(.+?)\s*-->/s)
          if (finalResultMatch) {
            const parsedResult = JSON.parse(finalResultMatch[1])
            if (parsedResult.success && parsedResult.images && parsedResult.images.length > 0) {
              this.$message.success('开始将生成的图片上传到WordPress...')

              // 将生成的图片自动上传到WordPress
              for (const image of parsedResult.images) {
                if (image.url) {
                  await this.handleImageUpload(image.url)
                }
              }

              // 刷新图片列表
              this.getList()

              // 显示成功通知
              this.$notify({
                title: 'AI插图应用成功',
                message: `成功生成并上传 ${parsedResult.images.length} 张插图到WordPress`,
                type: 'success',
                duration: 5000
              })
            } else {
              this.$message.error('AI生成的结果中没有有效的图片')
            }
          }
        } else {
          this.$message.warning('未找到可应用的图片结果')
        }
      } catch (error) {
        console.error('应用AI生成结果失败:', error)
        this.$message.error('应用AI生成结果失败：' + error.message)
      }
    }
  }
}
</script>

<style scoped>
.thumbnail-selector {
  padding: 20px;
}

.left-panel {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.right-panel {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.scrollable-container {
  height: 450px;
  overflow-y: auto;
}

.article-images {
  margin-bottom: 20px;
}

.images-grid-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.image-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: all 0.3s ease;
}

.image-item:hover {
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.image-upload-btn {
  width: 60px;
  font-size: 12px;
}

.preview-panel {
  margin-top: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.preview-image {
  margin-top: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
}

.image-cell {
  width: 150px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.preview-thumbnail {
  max-width: 140px;
  max-height: 90px;
  object-fit: contain;
  transition: transform 0.3s;
}

.preview-thumbnail:hover {
  transform: scale(1.05);
}

.image-link {
  display: inline-block;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-table {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}

.mb-4 {
  margin-bottom: 16px;
}

/* Element UI 样式覆盖 */
.el-table {
  margin-top: 15px;
}

.el-alert {
  margin-bottom: 20px;
}

h3, h4 {
  margin: 0 0 20px;
  color: #303133;
}

.el-button--primary.is-plain:hover {
  color: #409EFF;
  background: #ecf5ff;
  border-color: #b3d8ff;
}

/* AI生成插图样式 */
.ai-generate-section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.ai-generate-section h4 {
  margin: 0 0 10px;
  color: #303133;
}

.ai-tip {
  margin: 8px 0 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.style-selector {
  margin-bottom: 10px;
}

.style-selector .el-select {
  width: 100%;
}
</style>
